const popGoodsUrl = "http://123.207.32.32:8000/api/m3/home/data"
const multiData = "http://123.207.32.32:8000/api/m3/home/multidata"

const popGoodsEle = document.getElementById('pop-goods')
const loadMoreBtn = document.querySelector('.btn-load-more')

const slideContainer = document.querySelector('.slider-area .hero-slider-active')
const recommendContainer = document.querySelector('.banner-statistics .container .mbn-30')

let goodsList = []
let currentPage = 1
let goodsDetailList = []

//获取商品数据
function getPopGoods(page = 1) {
    ajax({
        url: popGoodsUrl,
        data: {
            type: "pop",
            page: page
        },
        success: function(data, string, xhr) {
            currentPage = page
            goodsList.push(...data.data.list)
            renderPopGoods(goodsList)
        },
        error: function(data, xhr, textStatus) {
            alert('加载失败！')
        }
    })
}

//获取轮播图以及推荐数据
function getMultiData() {
    ajax({
        url: multiData,
        success: function(data, status, xhr) {
            const bannerList = data.data.banner.list
            const recommendList = data.data.recommend.list
            renderSlide(bannerList)
            renderRecommend(recommendList)
                // console.log(data)

        }
    })
}

//渲染轮播图
function renderSlide(bannerList) {
    const slideHtmlArr = bannerList.map(item => {
        const slideHtml = `
        <div class="hero-single-slide ">
            <div class="hero-slider-item bg-img" data-bg="${item.image}">
                <div class="container">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="hero-slider-content slide-1">
                                <h2>${item.title}</h2>
                                <a href="${item.link}" class="btn-hero">shop now</a>
                            </div>
                        </div>
                    </div>
                </div>
               
            </div>
        </div>`
        return slideHtml

    })
    slideContainer.innerHTML = slideHtmlArr.join('')
    updateSlider()
}

//渲染推荐数据
function renderRecommend(recommendList) {
    const recommendHtmlArr = recommendList.map(item => {
        const recommendHtml = `
        <div class="col-md-3">
            <div class="banner-item mb-30">
                <figure class="banner-thumb">
                    <a href="javascript:void(0)">
                        <img src="${item.image}"
                            alt="${item.title}">
                    </a>
                    <figcaption class="banner-content">
                        <h2 class="text2">${item.title}</h2>
                        <a class="store-link" href="javascript:void(0)">点我</a>
                    </figcaption>
                </figure>
            </div>
        </div>`
        return recommendHtml
    })
    recommendContainer.innerHTML = recommendHtmlArr.join('')
}

//渲染商品数据
function renderPopGoods(goodsList) {
    const goodsHtmlArr = goodsList.map(item => {
        const itemHtml = `
        <div class="col-lg-3 col-md-3 col-sm-6">
            <div class="product-item mt-40">
                <figure class="product-thumb">
                    <a href="product-details.html">
                        <img class="pri-img" src="${item.show ? item.show.img : ''}" alt="product">
                        <img class="sec-img" src="/img/product/product-6.jpg" alt="product">
                    </a>
                    <div class="product-badge">
                        <div class="product-label new">
                            <span>流行</span>
                        </div>
                    </div>
                    <div class="button-group">
                        <a href="javascript:void(0)" data-toggle="tooltip" data-placement="left" title="收藏" data-event-type="fav" data-iid="${item.iid}">
                            <i class="lnr lnr-heart" data-event-type="fav" data-iid="${item.iid}"></i>
                        </a>
                        <a href="javascript:void(0)" data-toggle="modal" title="预览" data-target="#quick_view"  data-event-type="scan" data-iid="${item.iid}">
                            
                            <i class="lnr lnr-magnifier" data-event-type="scan" data-iid="${item.iid}"></i>
                        </a>
                        <a href="javascript:void(0)" data-toggle="tooltip" data-placement="left" title="添加购物车" data-event-type="addCart" data-iid="${item.iid}">
                            <i class="lnr lnr-cart" data-event-type="addCart" data-iid="${item.iid}"></i>
                        </a>
                    </div>
                </figure>
                <div class="product-caption">
                    <p class="product-name">
                        <a href="product-details.html">${item.title}</a>
                    </p>
                    <div class="price-box">
                        <span class="price-regular">￥${item.price}</span>
                        <span class="price-old"><del>${item.orgPrice}</del></span>
                    </div>
                </div>
            </div>
        </div>`
        return itemHtml
    })
    const goodsHtmlStr = goodsHtmlArr.join('')
    popGoodsEle.innerHTML = goodsHtmlStr
}

//绑定事件
function bindEvents() {
    //商品点击事件，如购物车，收藏等
    popGoodsEle.addEventListener('click', function(e) {
            const target = e.target
            const eventType = target.dataset.eventType
            const iid = target.dataset.iid
            if (eventType === "addCart") {
                const goods = goodsList.find(item => item.iid === iid)
                if (goods) {
                    cart.addToCart(goods)
                }
            } else if (eventType === "scan") {
                quickScan(iid)
            }

        })
        //加载跟更多事件
    loadMoreBtn.addEventListener('click', function(e) {
        e.preventDefault()
        getPopGoods(currentPage + 1)
    })

}

//快速预览商品详情数据
function quickScan(iid) {
    const goodsDetail = goodsDetailList.find(item => item.itemInfo.iid == iid)
    if (goodsDetail) {
        renderQuickScan(goodsDetail)
    } else {
        const url = `http://123.207.32.32:8000/api/m3/detail?iid=${iid}`
        ajax({
            url: url,
            success: function(data, status, xhr) {
                goodsDetailList.push(data.result)
                renderQuickScan(data.result)
            }
        })
    }

}

//
function renderQuickScan(result) {
    const topImages = result.itemInfo.topImages
    const productLargeSliderArr = topImages.map(item => {
        return `
        <div class="pro-large-img">
            <img src="${item}" alt="product-details" />
        </div>`
    })
    const proNavThumbArr = topImages.map(item => {
        return `
        <div class="pro-nav-thumb">
            <img src="${item}" alt="product-details" />
        </div>`
    })
    const productLargeSliderHtml = productLargeSliderArr.join('')
    const proNavThumbHtml = proNavThumbArr.join('')
    console.log(result)
    const scanHtml = ` 
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>
        <div class="modal-body">
            <!-- product details inner end -->
            <div class="product-details-inner">
                <div class="row">
                    <div class="col-lg-5 col-md-5">
                        <div class="product-large-slider">
                           ${productLargeSliderHtml}
                        </div>
                        <div class="pro-nav slick-row-10 slick-arrow-style">
                           ${proNavThumbHtml}
                        </div>
                    </div>
                    <div class="col-lg-7 col-md-7">
                        <div class="product-details-des quick-details">
                            <h3 class="product-name">${result.itemInfo.title}</h3>
                            <div class="ratings d-flex">
                                <span><i class="lnr lnr-star"></i></span>
                                <span><i class="lnr lnr-star"></i></span>
                                <span><i class="lnr lnr-star"></i></span>
                                <span><i class="lnr lnr-star"></i></span>
                                <span><i class="lnr lnr-star"></i></span>
                                <div class="pro-review">
                                    <span>${result.rate.cRate}条评论</span>
                                </div>
                            </div>
                            <div class="price-box">
                                <span class="price-regular">${result.itemInfo.price}</span>
                                <span class="price-old"><del>${result.itemInfo.oldPrice || ""}</del></span>
                                <span class="price-discount">${result.itemInfo.discountDesc}</span>
                            </div>
                            <div class="availability">
                                <i class="fa fa-check-circle"></i>
                                <span>剩余库存${result.skuInfo.totalStock}</span>
                            </div>
                            <p class="pro-desc">${result.itemInfo.desc}</p>
                            <div class="quantity-cart-box d-flex align-items-center">
                                <h5>qty:</h5>
                                <div class="quantity">
                                    <div class="pro-qty"><input type="text" value="1"></div>
                                </div>
                                <div class="action_link">
                                    <a class="btn btn-cart2" href="javascript:void(0)">添加到购物车</a>
                                </div>
                            </div>
                            <div class="useful-links">
                                <a href="javascript:void(0)" data-toggle="tooltip" title="Compare"><i class="lnr lnr-sync"></i>比较</a>
                                <a href="javascript:void(0)" data-toggle="tooltip" title="Wishlist"><i class="lnr lnr-heart"></i>收藏清单</a>
                            </div>
                            <div class="like-icon">
                                <a class="facebook" href="#"><i class="fa fa-facebook"></i>like</a>
                                <a class="twitter" href="#"><i class="fa fa-twitter"></i>tweet</a>
                                <a class="pinterest" href="#"><i class="fa fa-pinterest"></i>save</a>
                                <a class="google" href="#"><i class="fa fa-google-plus"></i>share</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div> <!-- product details inner end -->
        </div>
    </div>`
    const scanModal = document.querySelector('#quick_view .modal-content')
    scanModal.innerHTML = scanHtml

    updateQuickScan()
}
'javascript:void(0)'

function updateSlider() {
    var bgSelector = $(".bg-img");
    bgSelector.each(function(index, elem) {
        var element = $(elem),
            bgSource = element.data('bg');
        element.css('background-image', 'url(' + bgSource + ')');
    });

    $('.hero-slider-active').slick({
        autoplay: true,
        fade: true,
        speed: 1000,
        dots: false,
        prevArrow: '<button type="button" class="slick-prev"><i class="lnr lnr-chevron-left"></i></button>',
        nextArrow: '<button type="button" class="slick-next"><i class="lnr lnr-chevron-right"></i></button>',
        responsive: [{
            breakpoint: 992,
            settings: {
                arrows: false,
            }
        }]
    });

}

function updateQuickScan() {
    /*-------- prodct details slider active start --------*/
    $('.product-large-slider').slick({
        fade: true,
        arrows: false,
        asNavFor: '.pro-nav'
    });

    // product details slider nav active
    $('.pro-nav').slick({
        slidesToShow: 4,
        asNavFor: '.product-large-slider',
        centerMode: true,
        centerPadding: 0,
        focusOnSelect: true,
        prevArrow: '<button type="button" class="slick-prev"><i class="lnr lnr-chevron-left"></i></button>',
        nextArrow: '<button type="button" class="slick-next"><i class="lnr lnr-chevron-right"></i></button>',
        responsive: [{
            breakpoint: 576,
            settings: {
                slidesToShow: 3,
                arrows: false
            }
        }]
    });
    /*-------- prodct details slider active end --------*/

}

bindEvents()
getPopGoods()
getMultiData()